package com.idbk.chargestation.base;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import java.util.ArrayList;
import java.util.List;

/**
 * 继承了Activity，实现Android6.0的运行时权限检测
 * 需要进行运行时权限检测的Activity可以继承这个类
 * 
 * 创建时间：2016年5月27日 下午3:01:31
 * 项目名称： AMapLocationDemo
 * @author hongming.wang
 * 文件名称：PermissionsChecker.java
 * 类型名称：PermissionsChecker
 * @since 2.5.0
 */
public class CheckPermissionsActivity extends BaseActivity
		implements
			ActivityCompat.OnRequestPermissionsResultCallback {
	
	/**
	 * 需要进行检测的权限数组
	 */
	protected String[] needPermissions = {
			Manifest.permission.ACCESS_COARSE_LOCATION,
			Manifest.permission.ACCESS_FINE_LOCATION,
			Manifest.permission.WRITE_EXTERNAL_STORAGE,
			Manifest.permission.READ_EXTERNAL_STORAGE,
			Manifest.permission.READ_PHONE_STATE
			};
	
	private static final int PERMISSION_REQUEST_CODE = 0;
	
	/**
	 * 判断是否需要检测，防止不停的弹框
	 */
	private boolean isNeedCheck = true;
	
	@Override
	protected void onResume() {
		super.onResume();
		if(isNeedCheck){
			checkPermissions(needPermissions);
		}
	}
	
	/**
	 * 
	 * @param permissions permissions
	 * @since 2.5.0
	 *
	 */
	private void checkPermissions(String... permissions) {
		List<String> needRequestPermissionList = findDeniedPermissions(permissions);
		if (null != needRequestPermissionList
				&& needRequestPermissionList.size() > 0) {
			ActivityCompat.requestPermissions(this,
					needRequestPermissionList.toArray(
							new String[needRequestPermissionList.size()]),
					PERMISSION_REQUEST_CODE);
		}
	}

	/**
	 * 获取权限集中需要申请权限的列表
	 * 
	 * @param permissions permissions
	 * @return 需要申请权限的列表
	 * @since 2.5.0
	 *
	 */
	private List<String> findDeniedPermissions(String[] permissions) {
		List<String> needRequestPermissionList = new ArrayList<String>();
		for (String perm : permissions) {
			if (ContextCompat.checkSelfPermission(this,
					perm) != PackageManager.PERMISSION_GRANTED
					|| ActivityCompat.shouldShowRequestPermissionRationale(
							this, perm)) {
				needRequestPermissionList.add(perm);
			} 
		}
		return needRequestPermissionList;
	}

	/**
	 * 检测是否所有的权限都已经授权
	 * @param grantResults 授权grantResults
	 * @return 是否所有的权限都已经授权
	 * @since 2.5.0
	 *
	 */
	private boolean verifyPermissions(int[] grantResults) {
		for (int result : grantResults) {
			if (result != PackageManager.PERMISSION_GRANTED) {
				return false;
			}
		}
		return true;
	}

	@Override
	public void onRequestPermissionsResult(int requestCode,
										   @Nullable  String[] permissions, @Nullable int[] paramArrayOfInt) {
		if (requestCode == PERMISSION_REQUEST_CODE) {
			if (!verifyPermissions(paramArrayOfInt)) {
				showMissingPermissionDialog();
				isNeedCheck = false;
			}
		}
	}
		
}

